package com.frxuexi.repair.view

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.entity.RepairBeanItem
import com.frxuexi.base.http.Const
import com.frxuexi.base.mvi.BaseActivity
import com.frxuexi.base.mvi.RequestType
import com.frxuexi.base.mvi.UiState
import com.frxuexi.base.utils.ArouterManager
import com.frxuexi.base.utils.DateTimeUtils
import com.frxuexi.repair.R
import com.frxuexi.repair.RepairIntent
import com.frxuexi.repair.RepairViewModel
import com.frxuexi.repair.adapter.RepairImgAdapter
import com.frxuexi.repair.databinding.ActivityRepariAddBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/repair/RepariAddActivity")
@AndroidEntryPoint
class RepariAddActivity : BaseActivity<ActivityRepariAddBinding, RepairIntent, RepairViewModel>() {
    val areaList = mutableListOf<String>("A区停车场", "B区停车场", "C区停车场")
    var areaId = 0
    val repairImgAdapter by lazy { RepairImgAdapter() }
    val imgList = mutableListOf<String>()
    override fun getVM(): RepairViewModel {
        return viewModels<RepairViewModel>().value
    }

    override fun getBind(): ActivityRepariAddBinding {
        return ActivityRepariAddBinding.inflate(layoutInflater)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        when(it.type){
                            RequestType.DEFAULT->{
                                val data = it.data.toString().split(":")[1]
                                Log.i("lr", data)
                                imgList.add(
                                    "http://10.161.9.80:2209/images/repair/${SPUtils.getInstance().getInt(Const.UID)}/${data}"
                                )
                            }
                            RequestType.ADD->{
                                ToastUtils.showLong("添加成功")
                                finish()
                            }

                            else -> {}
                        }

                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        binding.headRepairAdd.apply {
            headBack.setOnClickListener {
                finish()
            }
            headTitle.setText("报修维修")
            headAdd.setOnClickListener {
                val phone = binding.repairaddPhone.text.toString()
                val desc = binding.repairaddRemark.text.toString()
                val user = binding.repairaddUser.text.toString()
                val imgs = imgList.joinToString(",")
                val item = RepairBeanItem(
                    phone,
                    desc,
                    imgs,
                    null,
                    "WX${DateTimeUtils.getDateTimeString()}",
                    "待处理",
                    areaId.toString(),
                    user,
                    DateTimeUtils.getDateTime(System.currentTimeMillis()),
                    SPUtils.getInstance().getInt(Const.UID)
                )
                vm.sendIntent(RepairIntent.addRepair(item))
            }
        }

        binding.repairaddUser.setText(SPUtils.getInstance().getString(Const.UNAME))

        val areaAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, areaList)
        areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.repairaddLocation.adapter = areaAdapter
        binding.repairaddLocation.onItemSelectedListener =
            object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
//                area=areaList[position]
                    areaId = position + 1
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {

                }
            }

        binding.repairaddImg.setOnClickListener {
            if (repairImgAdapter.data.size < 4) {
                PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE).selectPicture()
            } else {
                ToastUtils.showLong("已达到最大限制")
            }
        }

        binding.repairaddRv.apply {
            adapter = repairImgAdapter
            layoutManager = GridLayoutManager(this@RepariAddActivity, 3)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE && resultCode == RESULT_OK) {
            val pictureBean =
                data?.extras?.getParcelable<PictureBean>(PictureSelector.PICTURE_RESULT)
            val path = pictureBean?.path!!
            repairImgAdapter.addData(path)
            repairImgAdapter.notifyDataSetChanged()
            val split = path.split(Regex("[/]"))
            val name = split.get(split.lastIndex)
            vm.sendIntent(RepairIntent.upload(name, path))
        }
    }

}